package com.shawn.baseappbygroovydsl.ui.views

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat.getSystemService
import androidx.recyclerview.widget.LinearLayoutManager
import com.shawn.baseappbygroovydsl.R
import com.shawn.baseappbygroovydsl.bean.BeanTask
import com.shawn.baseappbygroovydsl.component.ItemDecorationTask
import com.shawn.baseappbygroovydsl.databinding.FragmentRecyclerviewBinding
import com.shawn.baseappbygroovydsl.databinding.FragmentTouchTestBinding
import com.shawn.baseappbygroovydsl.ui.adapter.AdapterRecyclerViewStyle1
import com.shawn.baseappbygroovydsl.ui.base.FragmentBase
import com.shawn.baseappbygroovydsl.utils.ExtensionCommon.dp
import com.shawn.baseappbygroovydsl.utils.UtilView

class TouchTestFragment  : FragmentBase<FragmentTouchTestBinding>(R.layout.fragment_touch_test) {
    private var screenWidth = 0
    private var screenHeight = 0
    private var dX = 0f
    private var dY = 0f
    private val initialMap = mutableMapOf<View, Pair<Float, Float>>()
    private val initialMapView = mutableMapOf<View, View?>()
    private val initialMapResult = mutableMapOf<View, String>()
    companion object {
        fun newInstance(): TouchTestFragment {
            val args = Bundle()
            val fragment = TouchTestFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onKeyCodeBack(): Boolean {
        return false
    }

    override fun statusBar() {

    }

    @SuppressLint("ClickableViewAccessibility")
    override fun lazyLoad() {
        screenWidth = requireActivity().resources.displayMetrics.widthPixels
        screenHeight = requireActivity().resources.displayMetrics.heightPixels
        mBind.rl11.post {
            // 记录初始位置
            initialMap[mBind.rl11] = Pair(mBind.rl11.x, mBind.rl11.y)
        }
        mBind.rl22.post {
            // 记录初始位置
            initialMap[mBind.rl22] = Pair(mBind.rl22.x, mBind.rl22.y)
        }
        mBind.rl33.post {
            // 记录初始位置
            initialMap[mBind.rl33] = Pair(mBind.rl33.x, mBind.rl33.y)
        }
        mBind.btnReset.setOnClickListener {
            resetView()
        }
        mBind.btnCommit.setOnClickListener {
            val result = StringBuilder()
            result.append(initialMapResult[initialMapView[mBind.rl1]]).append(", ")
            result.append(initialMapResult[initialMapView[mBind.rl2]]).append(", ")
            result.append(initialMapResult[initialMapView[mBind.rl3]])
            showToast(result.toString())
        }
        mBind.rl11.setOnTouchListener(TouchListener())
        mBind.rl22.setOnTouchListener(TouchListener())
        mBind.rl33.setOnTouchListener(TouchListener())

        initialMapResult[mBind.rl11] = "1"
        initialMapResult[mBind.rl22] = "2"
        initialMapResult[mBind.rl33] = "3"
    }

    private fun showToast(msg: String) {
        Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show()
    }

    private inner class TouchListener : View.OnTouchListener {
        override fun onTouch(view: View, event: MotionEvent): Boolean {
            return when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    // 记录触摸点与视图左上角的偏移量
                    dX = view.x - event.rawX
                    dY = view.y - event.rawY
                    true
                }
                MotionEvent.ACTION_MOVE -> {
                    // 计算新位置
                    var newX = event.rawX + dX
                    var newY = event.rawY + dY

                    // 限制X轴不超出屏幕
                    newX = newX.coerceIn(0f, (screenWidth - view.width).toFloat())

                    // 限制Y轴不超出屏幕
                    newY = newY.coerceIn(0f, ((screenHeight-48f.dp.toInt()) - view.height).toFloat())

                    // 应用新位置
                    moveView(view, newX, newY)
                    true
                }
                MotionEvent.ACTION_UP -> {
                    // 检查是否重叠
                    val move = checkAViewToBView(view)
                    moveView(view, move.first, move.second)
                    true
                }
                else -> false
            }
        }
    }

    private fun resetView() {
        moveView(mBind.rl11, initialMap[mBind.rl11]!!.first, initialMap[mBind.rl11]!!.second)
        moveView(mBind.rl22, initialMap[mBind.rl22]!!.first, initialMap[mBind.rl22]!!.second)
        moveView(mBind.rl33, initialMap[mBind.rl33]!!.first, initialMap[mBind.rl33]!!.second)
        initialMapView.clear()
    }

    private fun moveView(view: View, x: Float, y: Float) {
        view.animate()
            .x(x)
            .y(y)
            .setDuration(0)
            .start()
    }

    private fun isViewOverlapping(view1: View, view2: View): Boolean {
        val rect1 = Rect()
        view1.getGlobalVisibleRect(rect1)

        val rect2 = Rect()
        view2.getGlobalVisibleRect(rect2)

        return rect1.intersect(rect2)
    }

    private fun ressetViewMap(view: View) {
        if (initialMapView.isNotEmpty()) {
            initialMapView.entries.removeIf { it.value == view }
//            val iterator = initialMapView.iterator()
//            while (iterator.hasNext()) {
//                val entry = iterator.next()
//                if (entry.value == view) {
//                    iterator.remove()
//                    break
//                }
//            }
        }
    }

    private fun checkAViewToBView(viewA: View): Pair<Float, Float> {
        var toX = 0f
        var toY = 0f
        val viewB: View? = if (isAViewToBView(viewA, mBind.rl1)) {
            mBind.rl1
        } else if (isAViewToBView(viewA, mBind.rl2)) {
            mBind.rl2
        } else if (isAViewToBView(viewA, mBind.rl3)) {
            mBind.rl3
        } else {
            null
        }
        val origin = initialMap[viewA]!!
        if (viewB == null) {
            // 回到原位
            ressetViewMap(viewA)
            return origin
        }
        if (isSetView(viewB)) {
            showToast("填空位置已重叠")
            ressetViewMap(viewA)
            return origin
        }
        ressetViewMap(viewA)
        initialMapView[viewB] = viewA
        toX = viewB.x + (viewB.width - viewA.width) / 2
        toY = viewB.y + (viewB.height - viewA.height) / 2
        return Pair(toX, toY)
    }

    private fun isSetView(view: View): Boolean {
        return initialMapView[view] != null
    }

    private fun isAViewToBView(v: View, viewB: View): Boolean {
        // 检查是否在viewB范围内
        val viewBLoc = IntArray(2)
        viewB.getLocationOnScreen(viewBLoc)

        val viewALoc = IntArray(2)
        v.getLocationOnScreen(viewALoc)

        val viewAWidth = v.width
        val viewAHeight = v.height
        val viewBWidth = viewB.width
        val viewBHeight = viewB.height

        // 检查viewA中心点是否在viewB范围内
        val viewACenterX = viewALoc[0] + viewAWidth / 2
        val viewACenterY = viewALoc[1] + viewAHeight / 2
        return viewACenterX >= viewBLoc[0] &&
                viewACenterX <= viewBLoc[0] + viewBWidth &&
                viewACenterY >= viewBLoc[1] &&
                viewACenterY <= viewBLoc[1] + viewBHeight
    }

    override fun initClick() {

    }

    override fun getData() {

    }

    override fun getBind(view: View): FragmentTouchTestBinding {
        return FragmentTouchTestBinding.bind(view)
    }
}